<?php
class FrontendAction extends PiscesAction
{
	public function __construct()
	{
		parent::__construct();
		$this->data['menu']	= 'index';
	}
	
	public function beforeExecute()
	{
		parent::beforeExecute();
		
		//检查爬虫是否被屏蔽
		$settingService			= C('SettingService');
		$spiderSetting			= $settingService->get('spider_setting',true);
		if(!empty($spiderSetting))
		{
			$spider	= $this->getRobot();
			if($spider!==false)
			{
				if($spiderSetting[$spider]==1)
				{
					header("HTTP/1.0 404 Not Found");
					exit;
				}
			}
		}
		
		$this->data['site']		= $settingService->get('site_setting',true);
		$this->data['return']	= $settingService->get('return_setting',true);
		$apiSetting				= $settingService->get('api_setting',true);
		$this->data['taobao']['pid']	= $apiSetting['taobao_api_pid'];
		
		$this->data['cf']		= C('CommonFunction');
		
		$this->data['domain']	= $this->context->server('SERVER_NAME');
		$this->data['menuList']	= C('MenuService')->getList();
		
		$this->data['config']	= C('SettingService')->get('config_setting',true);
		
		$this->data['clickUrl']	= C('LtUrl')->generate('Default','Click',array('id'=>'defaultId'));
		
		$this->data['isRobot']	= $this->isRobot();
		
		$this->viewDir			= $this->viewDir.$this->data['site']['template'].'/';
		
		$apis = explode(',', $apiSetting['taobao_api_appkey']);
		$this->data['taobaoLoginUrl']	= $apiSetting['taobao_api_userlogin'].$apis[0];
		
		$this->getUserInfo();
	}
	
	public function getSeoStr($str,$replace)
	{
		foreach($replace as $k=>$v)
		{
			$str	= str_replace('{'.$k.'}',$v,$str);
		}
		return $str;
	}
	
	public function getSearchKeyword()
	{
		$fromUrl	= $this->context->referer('','',false);
		$sea1		= "baidu.com";//wd=
		$sea2		= "google.com";//q=
		$sea3		= "soso.com";//w=
		$sea4		= "sogou.com";//w=
		$keyword	= "";
		$exist1		= preg_match("/\b{$sea1}\b/",$fromUrl);
		$exist2		= preg_match("/\b{$sea2}\b/",$fromUrl);
		$exist3		= preg_match("/\b{$sea3}\b/",$fromUrl);
		$exist4		= preg_match("/\b{$sea4}\b/",$fromUrl);
		if($exist1)
		{
			$source 	= $fromUrl;
			$start		= strripos($fromUrl,'wd=');
			$source		= substr($source,$start+3);
			$start		= stripos($source,'&');
			if($start>0)
			{
				$keyword		= substr($source,0,$start);
			}
			else
			{
				$keyword		= substr($source,0);
			}
			$keyword			= urldecode($keyword);
			$keyword			= iconv('GBK','UTF-8',$keyword);
		}
		elseif($exist2)
		{
			$source 	= $fromUrl;
			$start		= stripos($source,'q=');
			$source		= substr($source,$start+strlen('q='));
			$start		= stripos($source,'&');
			if($start>0)
			{
				$start			= stripos($source,'&');
				$keyword		= substr($source,0,$start);
			}
			else
			{
				$keyword		= substr($source,0);
			}
			$keyword			= urldecode($keyword);
		}
		elseif($exist3)
		{
			$source 	= $fromUrl;
			$start		= stripos($source,'w=');
			$source		= substr($source,$start+strlen('w='));
			$start		= stripos($source,'&');
			if($start>0)
			{
				$start			= stripos($source,'&');
				$keyword		= substr($source,0,$start);
			}
			else
			{
				$keyword		= substr($source,0);
			}
			$keyword			= urldecode($keyword);
			$keyword			= iconv('GBK','UTF-8',$keyword);
		}
		elseif($exist4)
		{
			$source 	= $fromUrl;
			$start		= stripos($source,'query=');
			$source		= substr($source,$start+strlen('query='));
			$start		= stripos($source,'&');
			if($start>0)
			{
				$start			= stripos($source,'&');
				$keyword		= substr($source,0,$start);
			}
			else
			{
				$keyword		= substr($source,0);
			}
			$keyword			= urldecode($keyword);
			$keyword			= iconv('GBK','UTF-8',$keyword);
		}
		
		$keyword	= str_replace("\\",'',str_replace("'",'',$keyword));
		return $keyword;
	}
	
	private function getRobot()
	{
		if (empty($_SERVER['HTTP_USER_AGENT']))
		{
			return false;
		}
		
		$searchEngineBot = array(
			'googlebot'=>'google',
			'mediapartners-google'=>'google',
			'baiduspider'=>'baidu',
			'msnbot'=>'msn',
			'yodaobot'=>'yodao',
			'youdaobot'=>'yodao',
			'yahoo! slurp'=>'yahoo',
			'yahoo! slurp china'=>'yahoo',
			'iaskspider'=>'iask',
			'sogou web spider'=>'sogou',
			'sogou push spider'=>'sogou',
			'sosospider'=>'soso',
			'spider'=>'other',
			'crawler'=>'other',
		);
		
		$spider = strtolower($_SERVER['HTTP_USER_AGENT']);
		foreach ($searchEngineBot as $key => $value)
		{  
			if (strpos($spider, $key)!== false)
			{
				return $value;
			}
		}
		
		return false;
	}
	
	public function isRobot()
	{
		if($this->getRobot()!==false)
		{
			return true;
		}
		return false;
	}
	
	private function getUserInfo()
	{
		//优先用cookie中取登陆信息
		$cookie = C('LtCookie');
		$authCode 	= $cookie->getCookie('user_auth');
		if($authCode)
		{
			list($id, $username, $password, $expire) = explode("\t", $authCode);
			$userService	= C('UserService');
			$user 			= $userService->checkLogin($id,$password);
			if ($user && $user['id'] == $id)
			{
				if(empty($user['logo']))
				{
					$user['logo']	= $this->data['baseurl'].'images/avatar-120.png';
				}
				$this->data['user']	= $user;
				//更新cookie
				if($expire-time()<600)
				{
					$expire		= time() + 1200;
					$authCode 	= $user['id'] . "\t" . $user['username']. "\t" .$user['password']. "\t" .$expire;
					$cookie->setCookie('user_auth', $authCode, $expire);
				}
			}
			else
			{
				$this->data['user'] = '';
				$cookie->delCookie('user_auth');
			}
		}
		
		//是否强制从taobao登录用户中获取信息，给后台获取报表用
		$forceLogin = $cookie->getCookie('forcelogin');
		if($user && $forceLogin!=1)
		{
			return $user;
		}
		
		$topParams 	= $this->context->get('top_parameters');
		$topSign	= $this->context->get('top_sign');
		$topSession	= $this->context->get('top_session');
		if(empty($topParams) || empty($topSign) || empty($topSession))
		{
			return false;
		}
		
		$apiSetting = C('SettingService')->get('api_setting',true);
		$apiKeys = explode(',', $apiSetting['taobao_api_appkey']);
		$apiSecrets = explode(',', $apiSetting['taobao_api_appsecret']);
		
		$appKey = $apiKeys[0];
		$appSecret = $apiSecrets[0];
		$sign = base64_encode(md5($appKey.$topParams.$topSession.$appSecret, true));
		if($sign!=$topSign)
		{
			return false;
		}
		
		//判断是否需要写sessionKey的cookie
		if($forceLogin==1)
		{
			//写入sessionKey
			$cookie->setCookie('sessionkey', $topSession, time() + 7200);
			$cookie->delCookie('forcelogin');
		}
		
		$str	= base64_decode($topParams);
		$tmp	= explode('&',$str);
		$info	= array();
		foreach($tmp as $v)
		{
			$tt				= explode('=',$v);
			if(count($tt)==2)
			{
				$info[$tt[0]]	= $tt[1];
			}
		}
		$userId		= $info['visitor_id'];
		$userName	= iconv('GBK','UTF-8',$info['visitor_nick']);
		if(empty($userName))
		{
			return false;
		}
		
		//从数据库中取用户
		$userService	= C('UserService');
		$user		= $userService->getUserByTaobaoNick($userName);
		if(!$user)
		{
			//从开放平台获取用户，保存到数据库中
			$tmp	= C('UserService')->getUserFromTaobao($userName,$topSession);
			if($tmp)
			{
				$userInfo				= array();
				$userInfo['taobao_id']	= $tmp['user_id'];
				$userInfo['taobao_nick']= is_null($tmp['nick'])?$userName:$tmp['nick'];
				$userInfo['username']	= is_null($tmp['nick'])?$userName:$tmp['nick'];
				$userInfo['promoted']	= $tmp['promoted_type']=='authentication'?1:0;
				$userInfo['alipay_account']	= is_null($tmp['alipay_account'])?'':$tmp['alipay_account'];
				$userInfo['email']	= is_null($tmp['email'])?'':$tmp['email'];
			}
			else
			{
				$userInfo				= array();
				$userInfo['taobao_id']	= $userId;
				$userInfo['taobao_nick']= $userName;
				$userInfo['username']	= $userName;
				$userInfo['promoted']	= 0;
				$userInfo['alipay_account']	= '';
				$userInfo['email']		= '';
			}
			if(empty($userInfo['email']))
			{
				$userInfo['email']	= C('CommonFunction')->random(16).'@taozhangmen.net';
			}
			
			//检查用户名是否重名
			$tmp	= $userService->getUserByName($userInfo['username']);
			if($tmp)
			{
				$userInfo['username']	.= '@tb';
			}
			
			$secques		= intval(rand(10000,100000));
			$password		= C('CommonFunction')->random(16);
			$userInfo['password']	= $password;
			
			//如果设置了注册佣金，更新用户的余额
			$returnSetting	= C('SettingService')->get('return_setting',true);
			if($returnSetting['rate']>0 && $returnSetting['reg_money']>0)
			{
				$userInfo['money']	= $returnSetting['reg_money'];
			}
			
			$id	= $userService->add($userInfo);
			if($id>0)
			{
				$user	= $userService->get($id);
			}
		}
		
		if($user)
		{
			$this->data['user']	= $user;
			
			$expire		= time() + 1200;
			$authCode 	= $user['id'] . "\t" . $user['username']. "\t" .$user['password']. "\t" .$expire;
			C("LtCookie")->setCookie('user_auth', $authCode, $expire);
			
			//判断是否需要重定向
			$redirectUrl = $cookie->getCookie('redirect');
			if(empty($redirectUrl))
			{
				$redirectUrl = C('LtUrl')->generate('Default','Index');
			}
			$cookie->delCookie('redirect');
			$this->redirect($redirectUrl);
		}
		
		return $user;
	}
	
	protected function getProductIdFromUrl($url)
	{
		//本域名
		$domain		= $this->data['domain'];
		$tmp		= parse_url($url);
		$urlDomain	= $tmp['host'];
		$query		= $tmp['query'];
		//本站的，检查是否是商品详情页
		if(strtolower($domain)==strtolower($urlDomain))
		{
			$pre		= 'Default-View-id';
			$pre2		= 'Default/View/id';
			$shotCut 	= C('LtConfig')->get("router.short_cut");
			if(!empty($shotCut))
			{
				if(array_key_exists($pre,$shotCut))
				{
					$pre	= $shotCut[$pre];
				}
				if(array_key_exists($pre2,$shotCut))
				{
					$pre	= $shotCut[$pre2];
				}
			}
			$p				= strpos($tmp['path'],'/'.$pre);
			if($p!==false)
			{
				$path			= substr($tmp['path'],$p+strlen($pre)+2);
				$routingTable 	= C('LtConfig')->get("router.routing_table");
				$productId		= str_replace($routingTable['postfix'],'',$path);
				if(!is_numeric($productId))
				{
					$productId	= base64_decode($productId);
					$tmp		= explode('_',$productId);
					$productId	= $tmp[0];
				}
				return $productId;
			}
		}
		//本站非伪静态模式或者淘宝详情页URL
		if(preg_match('~id=([^&]*)~',$query,$m))
		{
			$productId	= $m[1];
			if(!is_numeric($productId))
			{
				$productId	= base64_decode($productId);
				$tmp		= explode('_',$productId);
				$productId	= $tmp[0];
			}
			return $productId;
		}
		
		return 0;
	}
}